package com.tegtech.starter.security.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.tegtech.common.constant.CacheKey;
import com.tegtech.common.constant.Constants;
import com.tegtech.common.exception.BusinessException;
import com.tegtech.common.exception.user.CaptchaException;
import com.tegtech.common.exception.user.CaptchaExpireException;
import com.tegtech.common.exception.user.UserPasswordNotMatchException;
import com.tegtech.module.auth.domain.LoginAgent;
import com.tegtech.module.auth.domain.LoginUser;
import com.tegtech.starter.manager.AsyncManager;
import com.tegtech.starter.redis.service.RedisCache;
import com.tegtech.starter.security.log.service.LoginLogTaskService;

/**
 * 登录校验方法
 * 
 * @author Jun
 */
@Component
public class SysLoginService {
	
	@Autowired
	private TokenService tokenService;

	@Resource
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisCache redisCache;

	/**
	 * 登录验证
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param code     验证码
	 * @param uuid     唯一标识
	 * @return 结果
	 */
	public String login(String username, String password, String code, String uuid) {
		// 验证码校验
		checkCaptcha(username, code, uuid);
		// 用户验证
		Authentication authentication = null;
		LoginAgent loginAgent = tokenService.getLoginAgent();
		try {
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				AsyncManager.me().execute(LoginLogTaskService.record(loginAgent, username, Constants.FAIL, "用户不存在/密码错误"));
				throw new UserPasswordNotMatchException();
			} else {
				AsyncManager.me().execute(LoginLogTaskService.record(loginAgent, username, Constants.FAIL, e.getMessage()));
				throw new BusinessException(e.getMessage());
			}
		}
		// 记录日志
		AsyncManager.me().execute(LoginLogTaskService.record(loginAgent, username, Constants.SUCCESS, "登录成功"));
		// 设置代理信息
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		loginUser.setAgent(loginAgent);
		// 生成token
		return tokenService.createToken(loginUser);
	}
	
	/**
	 * 校验验证码
	 * @param username 用户名
	 * @param captcha  验证码
	 * @param uuid     唯一标识
	 */
	private void checkCaptcha(String username, String code, String uuid) {
		String verifyKey = CacheKey.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisCache.get(verifyKey);
		if (captcha == null) {
			throw new CaptchaExpireException();
		}
		if (!code.equalsIgnoreCase(captcha)) {
			throw new CaptchaException();
		}
		redisCache.del(verifyKey);
	}
	
}
